<?php

namespace App\Service\VendorClient\Shophzlike;

use App\Service\Code\Normal;
use App\Service\BaseService;
use App\Model\PssModel\ServiceConfig;
use Service\AppService\IdService;
use App\Service\TaskServer\TaskWorker;

/**
 * 杭州里克供应商订单SDK
 * @author huj
 */
class ShophzlikeApiClient extends BaseService {
    //供应商编号
    const SUPPLIER_CODE = 'shophzlike';

    //配置文件
    private $config = [];

    public function __construct($apiBody = []) {
        $this->config = $apiBody;
    }

    /**
     * 创建订单
     * @param array $params
     * @return array
     */
    public function createOrder($param = []) {
        if (empty($param['supplierOrder']) || empty($param['orderGoods']) || empty($param['order']) || empty($param['binfo'])) {
            return Normal::returnCode(Normal::FAIL, "except param supplierOrder or orderGoods or order or binfo");
        }
        $orderInfo = $param['supplierOrder'];
        $goodsList = $param['orderGoods'];
        $order     = $param['order'];
        $binfo     = $param['binfo'];
        $order_sn  = $orderInfo['supplier_dsn'];
        //支付流水号
        $pay_sn = $order['paySerial'] ?? $orderInfo['pay_sn'];
        //订单时间
        $order_time = $orderInfo['cd'] ? date('Y-m-d H:i:s', $orderInfo['cd']) : date('Y-m-d H:i:s', time());
        //支付时间
        $pay_time = isset($order['payTime']) && !empty($order['payTime']) ? date('Y-m-d H:i:s', $order['payTime']) : date('Y-m-d H:i:s', time());
        //运费分摊
        $deliver_money = $orderInfo['deliver_money'];
        //下单支付的时候支付信息
        $apply_extends = @json_decode($orderInfo['apply_extends'], true);

        //判断支付方式是否存在
        $payCommanyCode = $apply_extends['payCommanyCode'] ?? '';
        $payCommanyCode = $order['payCommanyCode'] ?? $payCommanyCode;
        // $payWayInfo     = ServiceConfig::instance()->getConfigByEventsValue(self::SUPPLIER_CODE, ServiceConfig::TYPE_PAY, $payCommanyCode, false);
        // if (empty($payWayInfo)) {
        //     return Normal::returnCode(Normal::FAIL, "支付公司编码：【{$payCommanyCode}】未映射，请联系管理员处理");
        // }
        //获取下单商品信息
        $palceOrderGoods    = [];
        $totalGoodsMoney    = '0.00';
        $goodsTotalMoney    = '0.00';
        $goodsTotalMoneyNot = '0.00';
        $wayTaxFee          = '0.00';
        foreach ($goodsList as $key => $item) {
            $tax_rate         = bcadd('1', (string)$item['tax_rate'], 4);
            $price            = $item['price'];
            $spec_num         = $item['spec_num'];
            $quantity         = $item['quantity'];
            $supplier_skucode = $item['supplier_skucode'];
            $goods_type       = $item['goods_type'];
            //实际购买数量(下单数量 X 起售数量)
            $buyAcount = $spec_num * $quantity;
            // if ($key == 0) {
            //     $singleDeliveryMoney = bcdiv((string)$deliver_money, (string)$quantity, 3);
            //     $singleDeliveryMoney = bcmul((string)$singleDeliveryMoney, (string)100, 1);
            //     $singleDeliveryMoney = bcdiv((string)ceil($singleDeliveryMoney), (string)100, 2);
            //     $price               = bcadd((string)$price, (string)$singleDeliveryMoney, 2);
            // }
            //不含税价格
            $singleGoodsPrice = bcdiv((string)$price, (string)$tax_rate, 3);
            $singleGoodsPrice = bcmul((string)$singleGoodsPrice, (string)100, 1);
            $singleGoodsPrice = bcdiv((string)ceil($singleGoodsPrice), (string)100, 2);
            //商品不含税总价
            $goodsTotalPrice = bcmul((string)$singleGoodsPrice, (string)$quantity, 2);
            //含税总价
            $goodsTotalPriceTax = bcmul((string)$price, (string)$quantity, 2);
            //税费
            $tax    = bcsub((string)$price, (string)$singleGoodsPrice, 2);
            $taxAll = bcmul((string)$tax, (string)$quantity, 2);

            //判断是不是保税订单
            $taxAll = $goods_type == 1 ? $taxAll : 0;
            //不含税总金额
            $goodsTotalMoneyNot = bcadd((string)$goodsTotalMoneyNot, (string)$goodsTotalPrice, 2);
            //含税总金额
            $goodsTotalMoney = bcadd((string)$goodsTotalMoney, (string)$goodsTotalPriceTax, 2);
            //总税费
            $wayTaxFee = bcadd((string)$wayTaxFee, (string)$taxAll, 2);
            //下单商品组
            $goodsInfo         = [
                'goods_no' => $item['supplier_skucode'],//商品在仓库的编码
                'number'   => (int)$quantity,//发货数量
                'total'    => (int)(bcmul($goodsTotalPriceTax, '100')),//单品含税含优惠总金额（税+商品金额）*商品数量
            ];
            $palceOrderGoods[] = $goodsInfo;
        }
        // $couponFee    = $goodsTotalMoney > $orderInfo['real_total_money'] ? bcsub($goodsTotalMoney, $orderInfo['real_total_money'], 2) : '0.00';
        $requestParam = [
            'order_no'     => $order_sn,//订单号
            'create_time'  => $order_time,//下单时间
            'pay_time'     => $pay_time,//支付时间
            'total_price'  => (int)(bcmul($orderInfo['real_total_money'], '100')),//订单应付总金额(含优惠金额)
            'total_tax'    => (int)(bcmul($wayTaxFee, '100')),//订单应付税额
            'total_fright' => (int)(bcmul($deliver_money, '100')),//订单实际运费(含税)，没有运费请填写0
            'f_discount'   => 0,//订单优惠金额(含税)，请填写总的优惠，没有请填写0
            'customs'      => [
                'idcard'         => $orderInfo['buyer_idcard'],//客户下单的身份证号码
                'idcard_name'    => $orderInfo['buyer_realname'],//客户下单的身份证名字
                'plaform_code'   => $order['enterpriseNum'] ?? $apply_extends['enterpriseNum'],//下单平台在海关总署的编码
                'pay_id'         => $payCommanyCode,//支付公司在海关的编码，详情见文档附件
                'pay_no'         => $order['paySerial'] ?? $apply_extends['paySerial'],//支付单号 支付流水号
                'order_decla_no' => $order_sn,//在海关的报关单号
            ],
            'address'      => [
                'consignee'       => $orderInfo['receive_name'],//收货人姓名
                'consignee_phone' => $orderInfo['recveive_phone'],//收货人电话
                'province'        => $orderInfo['province'],//省
                'city'            => $orderInfo['city'],//市
                'area'            => $orderInfo['district'],//区
                'address'         => $orderInfo['receive_address'],//具体地址
            ],
            'goods'        => $palceOrderGoods,
        ];
        $data         = [
            'method' => 'createOrder',
            'data'   => json_encode($requestParam, JSON_UNESCAPED_UNICODE),
        ];
        return $this->execute($data);
    }

    /**
     * 获取取消订单
     */
    public function cancelOrder($params = []) {
        $queryParam = [
            'order_no' => $params['supplierOrder']['supplier_dsn'],//平台单号（下单推送的order_no）
            'order_decla_no' => $params['supplierOrder']['supplier_dsn'],//报关单号
        ];
        $data = [
            'method' => 'cancelOrder',
            'data'   => json_encode($queryParam, JSON_UNESCAPED_UNICODE),
        ];
        return $this->execute($data);
    }

    /**
     * 获取物流信息
     * @param array $param
     */
    public function queryOrderExpress( $params = [] ) {
        $queryParam = [
            'order_no' => $params['supplier_dsn']
        ];
        $data         = [
            'method' => 'orderExpress',
            'data'   => json_encode($queryParam, JSON_UNESCAPED_UNICODE),
        ];
        return $this->execute($data);
    }

    /**
     * 签名
     * @param $data
     * @return string
     */
    public function sign($data) {
        ksort($data);
        $arr = [];
        foreach ($data as $k => $v) {
            $arr[] = "{$k}={$v}";
        }

        $str = implode("&", $arr) . $this->config['appSecret'];
        $str = md5($str);
        return strtoupper($str);
    }

    /**
     * 生成不大于32位随机数
     * @param int $length 生成随机数的长度
     */
    public static function randomStr($length = 32) {
        $pool = '0123456789abcdefghijklmnopqrstuvwxyz';
        return mb_substr(str_shuffle(str_repeat($pool, $length)), 0, $length, 'UTF-8');
    }

    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute($param = []) {
        $method = $param['method'];
        $data   = $param['data'];
        if (!isset($this->config[$method])) {
            return Normal::returnCode(Normal::FAIL, "请求路由未设置");
        }
        if (empty($param['data'])) {
            return Normal::returnCode(Normal::FAIL, "数据不能为空");
        }
        $url = $this->config['baseUrl'];
        if (empty($url)) {
            return Normal::returnCode(Normal::FAIL, "接口地址不能为空");
        }
        $pushData         = [
            'warehouse_no' => $this->config['warehouseNo'],
            'charset'      => 'UTF-8',
            'customer_no'  => $this->config['customerNo'],
            'nonce_str'    => self::randomStr(),
            'method'       => $this->config[$method],
            'sign_type'    => 'MD5',
            'query_params' => $data,
        ];
        $pushData['sign'] = $this->sign($pushData);
        $parameter        = [
            [
                'tag'    => self::SUPPLIER_CODE . '_' . $param['method'],
                'uid'    => IdService::instance()->getOtherID(),
                'url'    => $url,
                'data'   => $pushData,
                'method' => 'post',
                'format' => 'form-data',
                'header' => [],
            ],
        ];
        $resTask          = TaskWorker::instance()->addTask($parameter);
        $resTask          = current($resTask);
        $result           = @json_decode($resTask['response']['result'], true);
        if (isset($result['errorCode']) && $result['errorCode'] === 0) {
            return Normal::returnCode(Normal::SUC, "操作成功", $result);
        } else {
            $msg = $result['errorMsg'] ?? '请求失败';
            return Normal::returnCode(Normal::FAIL, $msg);
        }
    }


}